<?php
namespace app\api\controller;
use think\Lang;
use think\Db;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 卖家代金券控制器
 */
class Sellervoucher extends MobileSeller {
    private $quotastate_arr;
    private $templatestate_arr;

    public function _initialize() {
        parent::_initialize(); // TODO: Change the autogenerated stub
        Lang::load(APP_PATH . 'home/lang/'.config('default_lang').'/sellervoucher.lang.php');
        if (config('voucher_allow') != 1) {
            ds_json_encode(10001,lang('voucher_unavailable'));
        }
        //套餐状态
        $this->quotastate_arr = array(
            'activity' => array(1, lang('voucher_quotastate_activity')),
            'cancel' => array(2, lang('voucher_quotastate_cancel')),
            'expire' => array(3, lang('voucher_quotastate_expire'))
        );
        //代金券模板状态
        $this->templatestate_arr = array(
            'usable' => array(1, lang('voucher_templatestate_usable')),
            'disabled' => array(2, lang('voucher_templatestate_disabled'))
        );
    }
    /**
     * @api {POST} api/Sellervoucher/templatelist 代金券列表
     * @apiVersion 1.0.0
     * @apiGroup Sellervoucher
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {String} txt_keyword 关键词
     * @apiParam {String} select_state 状态 1:有效 2:失效
     * @apiParam {String} txt_startdate 有效期开始时间 YYYY-MM-DD
     * @apiParam {String} txt_enddate 有效期结束时间 YYYY-MM-DD
     * @apiParam {String} page 页码
     * @apiParam {String} pagesize 每页显示数量
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object} result.current_quota  代金券活动信息 （返回字段参考voucherquota）
     * @apiSuccess {String} result.promotion_voucher_price  购买代金劵活动所需费用
     * @apiSuccess {String} result.voucher_storetimes_limit  每月最多可以发布的代金劵促销活动数量
     * @apiSuccess {Object} result.vouchertemplate_list  代金券模板列表 （返回字段参考vouchertemplate）
     * @apiSuccess {Int} result.page_total  总页数
     * @apiSuccess {Boolean} result.hasmore  是否有更多 true是false否
     */
    public function templatelist() {
        //检查过期的代金券模板状态设为失效
        $this->check_voucher_template_expire();
        $voucher_model = model('voucher');
        $isPlatformStore=$this->store_info['is_platform_store']?true:false;
        $current_quota=null;
        if (!$this->store_info['is_platform_store']) {
            //查询是否存在可用套餐
            $current_quota = $voucher_model->getVoucherquotaCurrent($this->store_info['store_id']);
        }
        //查询列表
        $param = array();
        $param['vouchertemplate_store_id'] = $this->store_info['store_id'];
        if (trim(input('param.txt_keyword'))) {
            $param['vouchertemplate_title'] = array('like', '%' . trim(input('param.txt_keyword')) . '%');
        }
        $select_state = intval(input('param.select_state'));
        if ($select_state) {
            $param['vouchertemplate_state'] = $select_state;
        }
        if (input('param.txt_startdate')) {
            $param['vouchertemplate_enddate'] = array('egt', strtotime(input('param.txt_startdate')));
        }
        if (input('param.txt_enddate')) {
            $param['vouchertemplate_startdate'] = array('elt', strtotime(input('param.txt_enddate')));
        }

        $vouchertemplate_list_ = db('vouchertemplate')->where($param)->order('vouchertemplate_id desc')->paginate(10, false, ['query' => request()->param()]);

        $vouchertemplate_list = $vouchertemplate_list_->items();
        foreach ($vouchertemplate_list as $key => $val) {

            if (!$val['vouchertemplate_customimg'] || !file_exists(BASE_UPLOAD_PATH . DS . ATTACH_VOUCHER . DS . $this->store_info['store_id'] . DS . $val['vouchertemplate_customimg'])) {
                $vouchertemplate_list[$key]['vouchertemplate_customimg'] = UPLOAD_SITE_URL . DS . default_goodsimage(60);
            } else {
                $vouchertemplate_list[$key]['vouchertemplate_customimg'] = UPLOAD_SITE_URL . DS . ATTACH_VOUCHER . DS . $this->store_info['store_id'] . DS . $val['vouchertemplate_customimg'];
            }
        }


        $result = array_merge(array('vouchertemplate_list' => $vouchertemplate_list,'current_quota'=>$current_quota,'isPlatformStore'=>$isPlatformStore,'promotion_voucher_price'=>config('promotion_voucher_price'),'voucher_storetimes_limit'=>config('voucher_storetimes_limit')), mobile_page($vouchertemplate_list_));
        ds_json_encode(10000, '查询成功', $result);
    }

    /**
     * @api {POST} api/Sellervoucher/quotaadd 购买套餐
     * @apiVersion 1.0.0
     * @apiGroup Sellervoucher
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} quota_quantity 购买数量
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.voucherquota_endtime  代金券活动结束时间
     */
    public function quotaadd() {
        if(intval(config('promotion_voucher_price'))==0){
                ds_json_encode(10001,lang('param_error'));
            }
            $quota_quantity = intval(input('post.quota_quantity'));
            if ($quota_quantity <= 0 || $quota_quantity > 12) {
                ds_json_encode(10001,lang('voucher_apply_num_error'));
            }
            //获取当前价格
            $current_price = intval(config('promotion_voucher_price'));

            $voucher_model = model('voucher');

            //获取该用户已有套餐
            $current_quota = $voucher_model->getVoucherquotaCurrent($this->store_info['store_id']);
            $quota_add_time = 86400 * 30 * $quota_quantity;
            if (empty($current_quota)) {
                //生成套餐
                $param = array();
                $param['voucherquota_memberid'] = $this->member_info['member_id'];
                $param['voucherquota_membername'] = $this->member_info['member_name'];
                $param['voucherquota_storeid'] = $this->store_info['store_id'];
                $param['voucherquota_storename'] = $this->store_info['store_name'];
                $param['voucherquota_starttime'] = TIMESTAMP;
                $param['voucherquota_endtime'] = TIMESTAMP + $quota_add_time;
                $param['voucherquota_state'] = 1;
                $reault = db('voucherquota')->insert($param);
            } else {
                $param = array();
                $param['voucherquota_endtime'] = $current_quota['voucherquota_endtime']+$quota_add_time;
                $reault = db('voucherquota')->where(array('voucherquota_id' => $current_quota['voucherquota_id']))->update($param);
            }

            //记录店铺费用
            $this->recordStorecost($current_price * $quota_quantity, lang('buy_voucher_package'));

            $this->recordSellerlog(lang('buy') . $quota_quantity . lang('voucher_plan') . $current_price . lang('ds_yuan'));

            if ($reault) {
                ds_json_encode(10000,lang('voucher_apply_buy_succ'),array('voucherquota_endtime'=>$param['voucherquota_endtime']));
            } else {
                ds_json_encode(10001,lang('ds_common_op_fail'));
            }

    }


    /**
     * @api {POST} api/Sellervoucher/templateadd 代金券模版添加
     * @apiVersion 1.0.0
     * @apiGroup Sellervoucher
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {String} txt_template_title 代金券模版名称
     * @apiParam {String} txt_template_total 代金券总数
     * @apiParam {String} select_template_price 面额
     * @apiParam {String} txt_template_limit 订单限额
     * @apiParam {String} txt_template_describe 代金券模版描述
     * @apiParam {String} txt_template_enddate 有效期结束时间 YYYY-MM-DD
     * @apiParam {String} storeclass_id 所属店铺分类ID
     * @apiParam {String} eachlimit 每人限领张数
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function templateadd() {
        $voucher_model = model('voucher');
        $isPlatformStore = $this->store_info['is_platform_store'];
        $quotainfo = array();
        if (!$isPlatformStore) {
            //查询当前可以使用的套餐
            $quotainfo = $voucher_model->getVoucherquotaCurrent($this->store_info['store_id']);
            if (empty($quotainfo)) {
                if(intval(config('promotion_voucher_price'))==0){
                    $quotainfo=array('voucherquota_id'=>0,'voucherquota_starttime'=>TIMESTAMP,'voucherquota_endtime'=>TIMESTAMP+86400*30);//没有套餐时，最多一个月
                }else{
                    ds_json_encode(10001,lang('voucher_template_quotanull'));
                }
            }

            //查询该套餐下代金券模板列表
            $count = db('vouchertemplate')->where(array('vouchertemplate_quotaid' => $quotainfo['voucherquota_id'], 'vouchertemplate_state' => $this->templatestate_arr['usable'][0]))->count();
            if ($count >= config('voucher_storetimes_limit')) {
                $message = sprintf(lang('voucher_template_noresidual'), config('voucher_storetimes_limit'));
                ds_json_encode(10001,$message);
            }
        }
        $common_data=$this->common_data();
        $pricelist= $common_data['pricelist'];
            //验证提交的内容面额不能大于限额
            $data = [
                'txt_template_title' => input('post.txt_template_title'),
                'txt_template_total' => input('post.txt_template_total'),
                'select_template_price' => input('post.select_template_price'),
                'txt_template_limit' => input('post.txt_template_limit'),
                'txt_template_describe' => input('post.txt_template_describe'),
            ];

            $sellervoucher_validate = validate('sellervoucher');
            if (!$sellervoucher_validate->scene('templateadd')->check($data)) {
                ds_json_encode(10001,$sellervoucher_validate->getError());
            }
            //金额验证
            $price = intval(input('post.select_template_price')) > 0 ? intval(input('post.select_template_price')) : 0;
            foreach ($pricelist as $k => $v) {
                if ($v['voucherprice'] == $price) {
                    $chooseprice = $v; //取得当前选择的面额记录
                }
            }
            if (empty($chooseprice)) {
                ds_json_encode(10001,lang('voucher_template_pricelisterror'));
            }
            $limit = intval(input('post.txt_template_limit')) > 0 ? intval(input('post.txt_template_limit')) : 0;
            if ($price >= $limit){
                ds_json_encode(10001,lang('voucher_template_price_error'));
            }
                $insert_arr = array();
                $insert_arr['vouchertemplate_title'] = trim(input('post.txt_template_title'));
                $insert_arr['vouchertemplate_desc'] = trim(input('post.txt_template_describe'));
                $insert_arr['vouchertemplate_startdate'] = time(); //默认代金券模板的有效期为当前时间
                if (input('post.txt_template_enddate')) {
                    $enddate = strtotime(input('post.txt_template_enddate'));
                    if (!$isPlatformStore && $enddate > $quotainfo['voucherquota_endtime']) {
                        $enddate = $quotainfo['voucherquota_endtime'];
                    }
                    $insert_arr['vouchertemplate_enddate'] = $enddate;
                } else {//如果没有添加有效期则默认为套餐的结束时间
                    if ($isPlatformStore)
                        $insert_arr['vouchertemplate_enddate'] = time() + 2592000; // 自营店 默认30天到期
                    else
                        $insert_arr['vouchertemplate_enddate'] = $quotainfo['voucherquota_endtime'];
                }
                $insert_arr['vouchertemplate_price'] = $price;
                $insert_arr['vouchertemplate_limit'] = $limit;
                $insert_arr['vouchertemplate_store_id'] = $this->store_info['store_id'];
                $insert_arr['vouchertemplate_storename'] = $this->store_info['store_name'];
                $insert_arr['vouchertemplate_sc_id'] = intval(input('post.storeclass_id'));
                $insert_arr['vouchertemplate_creator_id'] = $this->seller_info['member_id'];
                $insert_arr['vouchertemplate_state'] = $this->templatestate_arr['usable'][0];
                $insert_arr['vouchertemplate_total'] = intval(input('post.txt_template_total')) > 0 ? intval(input('post.txt_template_total')) : 0;
                $insert_arr['vouchertemplate_giveout'] = 0;
                $insert_arr['vouchertemplate_used'] = 0;
                $insert_arr['vouchertemplate_gettype'] = 1;
                $insert_arr['vouchertemplate_adddate'] = TIMESTAMP;
                $insert_arr['vouchertemplate_quotaid'] = isset($quotainfo['voucherquota_id']) ? $quotainfo['voucherquota_id'] : 0;
                $insert_arr['vouchertemplate_points'] = $chooseprice['voucherprice_defaultpoints'];
                $insert_arr['vouchertemplate_eachlimit'] = intval(input('post.eachlimit')) > 0 ? intval(input('post.eachlimit')) : 0;
                //自定义图片
                if (!empty($_FILES['customimg']['name'])) {

                    $uploaddir = BASE_UPLOAD_PATH . DS . ATTACH_VOUCHER. DS . $this->store_info['store_id'] . DS;
                    $file_name = $this->store_info['store_id'] . '_' . date('YmdHis') . rand(10000, 99999);
                    $file_object = request()->file('customimg');
                    $info = $file_object->rule('uniqid')->validate(['ext' => ALLOW_IMG_EXT])->move($uploaddir, $file_name);
                    if ($info) {
                        $insert_arr['vouchertemplate_customimg'] = $info->getFilename();
                    }
                }
                $rs = db('vouchertemplate')->insert($insert_arr);
                if ($rs) {
                    ds_json_encode(10000,lang('ds_common_op_succ'));
                } else {
                    ds_json_encode(10001,lang('ds_common_op_fail'));
                }

    }

	/**
	 * 添加详情数据
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function templateadd_info()
	{
		$voucher_model = model('voucher');
		$isPlatformStore = $this->store_info['is_platform_store']?true:false;
		$quotainfo = array();
		if (!$isPlatformStore) {
			//查询当前可以使用的套餐
			$quotainfo = $voucher_model->getVoucherquotaCurrent($this->store_info['store_id']);
			if (empty($quotainfo)) {
				if(intval(config('promotion_voucher_price'))==0){
					$quotainfo=array('voucherquota_id'=>0,'voucherquota_starttime'=>TIMESTAMP,'voucherquota_endtime'=>TIMESTAMP+86400*30);//没有套餐时，最多一个月
				}else{
					ds_json_encode(10001,lang('voucher_template_quotanull'));
				}
			}

			//查询该套餐下代金券模板列表
			$count = db('vouchertemplate')->where(array('vouchertemplate_quotaid' => $quotainfo['voucherquota_id'], 'vouchertemplate_state' => $this->templatestate_arr['usable'][0]))->count();
			if ($count >= config('voucher_storetimes_limit')) {
				$message = sprintf(lang('voucher_template_noresidual'), config('voucher_storetimes_limit'));
				ds_json_encode(10001,$message);
			}
		}

		//查询面额列表
		$pricelist = db('voucherprice')->order('voucherprice asc')->select();
		//店铺分类
		$store_class = rkcache('storeclass', true);
		//查询店铺详情
		$store_info = model('store')->getStoreInfoByID($this->store_info['store_id']);
		$t_info = array(
			'vouchertemplate_title'=>'',
			'vouchertemplate_price'=>'',
			'vouchertemplate_total'=>'',
			'vouchertemplate_limit'=>'',
			'vouchertemplate_desc'=>'',
			'vouchertemplate_customimg'=>'',
			'vouchertemplate_enddate'=>'',
			'vouchertemplate_eachlimit'=>0,
			'vouchertemplate_sc_id'=>'',
		);
		$data['isPlatformStore']=$isPlatformStore;
		$data['store_info']=$store_info;
		$data['store_class']=array_values($store_class);
		$data['type']='add';
		$data['quotainfo']=$quotainfo;
		$data['pricelist']=$pricelist;
		$data['t_info']=$t_info;
		$common_data=$this->common_data();
		$data=array_merge($data,$common_data);
		ds_json_encode(10000,"查询成功",$data);
    }

    public function common_data(){
        //查询面额列表
        $pricelist = db('voucherprice')->order('voucherprice asc')->select();
        if (empty($pricelist)) {
            ds_json_encode(10001,lang('voucher_template_pricelisterror'));
        }
        return array('pricelist'=>$pricelist,'voucher_buyertimes_limit'=>config('voucher_buyertimes_limit'));
    }
    /**
     * @api {POST} api/Sellervoucher/get_common_data 代金券新增/编辑公共数据
     * @apiVersion 1.0.0
     * @apiGroup Sellervoucher
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object[]} result.pricelist  面额列表
     * @apiSuccess {Object[]} result.pricelist.voucherprice  面额
     * @apiSuccess {Object[]} result.pricelist.voucherprice_defaultpoints  兑换积分
     * @apiSuccess {Object[]} result.pricelist.voucherprice_describe  描述
     * @apiSuccess {Object[]} result.pricelist.voucherprice_id  面额ID
     * @apiSuccess {String} result.voucher_buyertimes_limit  买家最多只能拥有同一个店铺尚未消费抵用的店铺代金券最大数量
     */
    public function get_common_data(){
        $common_data=$this->common_data();
        ds_json_encode(10000,'',$common_data);
    }
    

    /**
     * @api {POST} api/Sellervoucher/templateadd 代金券模版编辑
     * @apiVersion 1.0.0
     * @apiGroup Sellervoucher
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} tid 代金券模版ID
     * @apiParam {String} txt_template_title 代金券模版名称
     * @apiParam {String} txt_template_total 代金券总数
     * @apiParam {String} select_template_price 面额
     * @apiParam {String} txt_template_limit 订单限额
     * @apiParam {String} txt_template_describe 代金券模版描述
     * @apiParam {String} txt_template_enddate 有效期结束时间 YYYY-MM-DD
     * @apiParam {String} storeclass_id 所属店铺分类ID
     * @apiParam {String} eachlimit 每人限领张数
     * @apiParam {Int} tstate 代金券模版状态 1:有效 2:失效
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function templateedit() {
        $t_id = intval(input('param.tid'));
        if ($t_id <= 0) {
            ds_json_encode(10001,lang('param_error'));
        }
        //查询模板信息
        $param = array();
        $param['vouchertemplate_id'] = $t_id;
        $param['vouchertemplate_store_id'] = $this->store_info['store_id'];
        $param['vouchertemplate_state'] = $this->templatestate_arr['usable'][0];
        $param['vouchertemplate_giveout'] = array('elt', '0');
        $param['vouchertemplate_enddate'] = array('gt', time());
        $t_info = db('vouchertemplate')->where($param)->find();
        if (empty($t_info)) {
            ds_json_encode(10001,lang('param_error'));
        }

        $isPlatformStore = $this->store_info['is_platform_store'];
        $this->assign('isPlatformStore', $isPlatformStore);
        $quotainfo = array();
        if (!$isPlatformStore) {
            //查询套餐信息
            $quotainfo = db('voucherquota')->where(array(
                        'voucherquota_id' => $t_info['vouchertemplate_quotaid'],
                        'voucherquota_storeid' => $this->store_info['store_id']
                    ))->find();
            if (empty($quotainfo)) {
                ds_json_encode(10001,lang('voucher_template_quotanull'));
            }
        }

           $common_data=$this->common_data();
            $pricelist= $common_data['pricelist'];
            //验证提交的内容面额不能大于限额
            $data = [
                'txt_template_title' => input('post.txt_template_title'),
                'txt_template_total' => input('post.txt_template_total'),
                'select_template_price' => input('post.select_template_price'),
                'txt_template_limit' => input('post.txt_template_limit'),
                'txt_template_describe' => input('post.txt_template_describe'),
            ];
            $sellervoucher_validate = validate('sellervoucher');
            if (!$sellervoucher_validate->scene('templateedit')->check($data)) {
                ds_json_encode(10001,$sellervoucher_validate->getError());

            }
            //金额验证
            $price = intval(input('post.select_template_price')) > 0 ? intval(input('post.select_template_price')) : 0;
            foreach ($pricelist as $k => $v) {
                if ($v['voucherprice'] == $price) {
                    $chooseprice = $v; //取得当前选择的面额记录
                }
            }
            if (empty($chooseprice)) {
                ds_json_encode(10001,lang('voucher_template_pricelisterror'));
            }
            $limit = intval(input('post.txt_template_limit')) > 0 ? intval(input('post.txt_template_limit')) : 0;
            if ($price >= $limit){
                ds_json_encode(10001,lang('voucher_template_price_error'));
            }
                $update_arr = array();
                $update_arr['vouchertemplate_title'] = trim(input('post.txt_template_title'));
                $update_arr['vouchertemplate_desc'] = trim(input('post.txt_template_describe'));
                if (input('post.txt_template_enddate')) {
                    $enddate = strtotime(input('post.txt_template_enddate'));
                    if (!$isPlatformStore && $enddate > $quotainfo['voucherquota_endtime']) {
                        $enddate = $quotainfo['voucherquota_endtime'];
                    }
                    $update_arr['vouchertemplate_enddate'] = $enddate;
                } else {//如果没有添加有效期则默认为套餐的结束时间
                    if ($isPlatformStore)
                        $update_arr['vouchertemplate_enddate'] = time() + 2592000; // 自营店 默认30天到期
                    else
                        $update_arr['vouchertemplate_enddate'] = $quotainfo['voucherquota_endtime'];
                }
                $update_arr['vouchertemplate_price'] = $price;
                $update_arr['vouchertemplate_limit'] = $limit;
                $update_arr['vouchertemplate_sc_id'] = intval(input('post.storeclass_id'));
                $update_arr['vouchertemplate_state'] = intval(input('post.tstate')) == $this->templatestate_arr['usable'][0] ? $this->templatestate_arr['usable'][0] : $this->templatestate_arr['disabled'][0];
                $update_arr['vouchertemplate_total'] = intval(input('post.txt_template_total')) > 0 ? intval(input('post.txt_template_total')) : 0;
                $update_arr['vouchertemplate_points'] = $chooseprice['voucherprice_defaultpoints'];
                $update_arr['vouchertemplate_eachlimit'] = intval(input('post.eachlimit')) > 0 ? intval(input('post.eachlimit')) : 0;
                //自定义图片
                if (!empty($_FILES['customimg']['name'])) {
                    $uploaddir = BASE_UPLOAD_PATH . DS . ATTACH_VOUCHER . DS .$this->store_info['store_id']. DS;
                    $file_name = $this->store_info['store_id'] . '_' . date('YmdHis') . rand(10000, 99999);
                    $file_object = request()->file('customimg');
                    $info = $file_object->validate(['ext' => ALLOW_IMG_EXT])->move($uploaddir, $file_name);
                    if ($info) {
                        //删除原图
                        if (!empty($t_info['vouchertemplate_customimg'])) {//如果模板存在，则删除原模板图片
                            @unlink(BASE_UPLOAD_PATH . DS . ATTACH_VOUCHER. DS .$this->store_info['store_id'] . DS . $t_info['vouchertemplate_customimg']);
                        }
                        $update_arr['vouchertemplate_customimg'] = $info->getFilename();
                    }
                }

                $rs = db('vouchertemplate')->where(array('vouchertemplate_id' => $t_info['vouchertemplate_id']))->update($update_arr);
                if ($rs) {
                    ds_json_encode(10000,lang('ds_common_op_succ'));
                } else {
                    ds_json_encode(10001,lang('ds_common_op_fail'));
                }

    }

	/**
	 * 编辑的时候用的
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function templateedit_info()
	{
		$t_id = intval(input('param.tid'));
		if ($t_id <= 0) {
			ds_json_encode(10001,lang('param_error'));
		}
		//查询模板信息
		$param = array();
		$param['vouchertemplate_id'] = $t_id;
		$param['vouchertemplate_store_id'] = $this->store_info['store_id'];
		$param['vouchertemplate_state'] = $this->templatestate_arr['usable'][0];
		$param['vouchertemplate_giveout'] = array('elt', '0');
		$param['vouchertemplate_enddate'] = array('gt', time());
		$t_info = db('vouchertemplate')->where($param)->find();

		if (empty($t_info)) {
			ds_json_encode(10001,lang('param_error'));
		}

		$data['isPlatformStore']=$isPlatformStore=$this->store_info['is_platform_store']?true:false;

		$quotainfo = array();
		if (!$isPlatformStore) {
			//查询套餐信息
			$quotainfo = db('voucherquota')->where(array(
				'voucherquota_id' => $t_info['vouchertemplate_quotaid'],
				'voucherquota_storeid' => $this->store_info['store_id']
			))->find();
			if (empty($quotainfo)) {
				ds_json_encode(10001,lang('voucher_template_quotanull'));
				//$this->error(lang('voucher_template_quotanull'), 'Sellervoucher/quotaadd');
			}
		}

		//查询面额列表
		$pricelist = db('voucherprice')->order('voucherprice asc')->select();
		if (empty($pricelist)) {
			ds_json_encode(10001,lang('voucher_template_pricelisterror'));
		}

		if (!$t_info['vouchertemplate_customimg'] || !file_exists(BASE_UPLOAD_PATH . DS . ATTACH_VOUCHER. DS .$this->store_info['store_id'] . DS . $t_info['vouchertemplate_customimg'])) {
			$t_info['vouchertemplate_customimg'] = UPLOAD_SITE_URL . DS . default_goodsimage(240);
		} else {
			$t_info['vouchertemplate_customimg'] = UPLOAD_SITE_URL . DS . ATTACH_VOUCHER. DS .$this->store_info['store_id'] . DS . $t_info['vouchertemplate_customimg'];
		}




		//店铺分类
		$store_class = rkcache('storeclass', true);
		//查询店铺详情
		$store_info = model('store')->getStoreInfoByID($this->store_info['store_id']);
		$t_info['vouchertemplate_sc_name']="";
		if(isset($t_info['vouchertemplate_sc_id']) && !empty($t_info['vouchertemplate_sc_id'])){
			foreach($store_class as $v){
				if($t_info['vouchertemplate_sc_id'] == $v['storeclass_id']){
					$t_info['vouchertemplate_sc_name']=$v['storeclass_name'];
				}
			}
		}

		$data['type']='edit';
		$data['t_info']=$t_info;
		$data['store_class']=array_values($store_class);
		$data['store_info']=$store_info;
		$data['quotainfo']=$quotainfo;
		$data['pricelist']=$pricelist;

		$common_data=$this->common_data();
		$data=array_merge($data,$common_data);
		ds_json_encode(10000,"查询成功",$data);
    }

    /**
     * @api {POST} api/Sellervoucher/templatedel 删除代金券
     * @apiVersion 1.0.0
     * @apiGroup Sellervoucher
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} tid 代金券模版ID
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function templatedel() {
        $t_id = intval(input('param.tid'));
        if ($t_id <= 0) {
            ds_json_encode(10001,lang('param_error'));
        }
        //查询模板信息
        $param = array();
        $param['vouchertemplate_id'] = $t_id;
        $param['vouchertemplate_store_id'] = $this->store_info['store_id'];
        $param['vouchertemplate_giveout'] = array('elt', '0'); //会员没领取过代金券才可删除
        $t_info = db('vouchertemplate')->where($param)->find();
        if (empty($t_info)) {
            ds_json_encode(10001,lang('param_error'));
        }
        $rs = db('vouchertemplate')->where(array('vouchertemplate_id' => $t_info['vouchertemplate_id']))->delete();
        if ($rs) {
            //删除自定义的图片
            if (trim($t_info['vouchertemplate_customimg'])) {
                @unlink(BASE_UPLOAD_PATH . DS . ATTACH_VOUCHER . DS . $this->store_info['store_id'] . DS . $t_info['vouchertemplate_customimg']);
            }
            ds_json_encode(10000,lang('ds_common_del_succ'));
        } else {
            ds_json_encode(10001,lang('ds_common_del_fail'));
        }
    }

    /**
     * 查看代金券详细
     */
    public function templateinfo() {
        $t_id = intval(input('param.tid'));
        if ($t_id <= 0) {
            ds_json_encode(10001,lang('param_error'), 'Sellervoucher/templatelist');
        }
        //查询模板信息
        $param = array();
        $param['vouchertemplate_id'] = $t_id;
        $param['vouchertemplate_store_id'] = $this->store_info['store_id'];
        $t_info = db('vouchertemplate')->where($param)->find();

	    //店铺分类
	    $store_class = rkcache('storeclass', true);
	    //查询店铺详情
	    $t_info['vouchertemplate_sc_name']="";
	    if(isset($t_info['vouchertemplate_sc_id']) && !empty($t_info['vouchertemplate_sc_id'])){
		    foreach($store_class as $v){
			    if($t_info['vouchertemplate_sc_id'] == $v['storeclass_id']){
				    $t_info['vouchertemplate_sc_name']=$v['storeclass_name'];
			    }
		    }
	    }
        ds_json_encode(10000,lang('ds_common_del_succ'),array('t_info'=>$t_info));
    }

    /*
     *
     * 把代金券模版设为失效
     */

    private function check_voucher_template_expire($voucher_template_id = '') {
        $where_array = array();
        if (empty($voucher_template_id)) {
            $where_array['vouchertemplate_enddate'] = array('lt', time());
        } else {
            $where_array['vouchertemplate_id'] = $voucher_template_id;
        }
        $where_array['vouchertemplate_state'] = $this->templatestate_arr['usable'][0];
        db('vouchertemplate')->where($where_array)->update(array('vouchertemplate_state' => $this->templatestate_arr['disabled'][0]));
    }


}
